/*
 * DA06.c
 *
 * Created: 4/16/2014 5:13:46 PM
 *  Author: mummm2
 */ 

/*
Avcc = 5v
Aref = 10uF
PinC5 is adc pin
PORTB0-3 is output to stepper motor
*/


#define F_CPU 8000000UL

#include <avr/io.h>
#include <util/delay.h>

void Delay(int);

int main(void){
	//Set PORTB1 pin as output
	DDRB = 0xFF;
	//TOP = ICR1;
	//output compare OC1A 8 bit non inverted PWM
	//Clear OC1A on Compare Match, set OC1A at TOP
	//Fast PWM
	//ICR1 = 20000 defines 50Hz pwm
	ICR1 = 20000;
	TCCR1A|=(0<<COM1A0)|(1<<COM1A1)|(0<<COM1B0)|(0<<COM1B1)|(0<<FOC1A)|(0<<FOC1B)|(1<<WGM11)|(0<<WGM10);
	
	TCCR1B|=(0<<ICNC1)|(0<<ICES1)|(1<<WGM13)|(1<<WGM12)|(0<<CS12)|(1<<CS11)|(0<<CS10);
	//start timer with prescaler 8
	
	double curr = 0;//saves the current value from analog in
	
	//data will be L-Justified, PC5 for analog reading, 5V external ref with 10uf cap
	ADMUX = (0<<REFS1) | (1<<REFS0) | (1<<ADLAR) | (0<<MUX3) | (1<<MUX2) | (0<<MUX1) | (1<<MUX0);
	//make ADC enable and select ck/128
	ADCSRA = (1<<ADEN) | (0<<ADSC) | (0<<ADATE) | (0<<ADIF) | (0<<ADIE) | (1<<ADPS2) | (1<<ADPS1) | (1<<ADPS0);
	
	//initialize value of ADC
	ADCSRA |= (1<<ADSC);			//Start Conversion
	while((ADCSRA&(1<<ADIF))==0);	//wait for end of conversion
	curr = ADC;

	OCR1A = 3000;
	_delay_ms(750);
	
	while(1){
		
		ADCSRA |= (1<<ADSC);			//Start Conversion
		while((ADCSRA&(1<<ADIF))==0);	//wait for end of conversion
		
		if(ADC > curr)		//if the new ADC value is greater than the current one
		OCR1A += 100;		//increase the degree angle
		else if (ADC < curr)//if the new ADC value is less than the current one
		OCR1A -= 100;		//decrease the degree angle
		
		curr = ADC;			//set the new ADC value as the current value
		
		if(OCR1A < 500)	 	//rotation cannot be smaller than 500
		OCR1A = 500;
		if(OCR1A > 3000)	//rotation cannot be larger than 3000
		OCR1A = 3000;
		
		_delay_ms(750);
	}
}
